package net.java.mediasystems.web.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.lang3.StringUtils;

import net.java.mediasystems.database.core.model.StorageContainer;
import net.java.mediasystems.database.core.service.StorageContainerService;

public class StorageContainerConverter implements Converter {
	
	private List<StorageContainer> storageContainerList;
	
	private StorageContainerService storageContainerService;
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (!StringUtils.isEmpty(value)) {
			for (StorageContainer curStorageContainer : this.storageContainerList) {
				if (curStorageContainer.getId().longValue() == Long.parseLong(value)) {
					return curStorageContainer;
				}
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		StorageContainer storageContainer = (StorageContainer) value;
		return storageContainer.getId().toString();
	}

	/**
	 * Special Set()-Method: The StorageContainerList will be initialized immediately after setting the StorageContainerService.
	 * 
	 * @param storageContainerService StorageContainerService
	 */
	public void setStorageContainerService(StorageContainerService storageContainerService) {
		this.storageContainerService = storageContainerService;
		this.storageContainerList = this.storageContainerService.getAllStorageContainers();
	}
}
